package com.jason.mail;


import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * 发送邮件内容带图片
 *
 * @author qianliu86
 */
public class EmailHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(EmailHelper.class);

    private static final boolean AUTH = true;
    private static final String HOST = "pop.qq.com";
    private static final String PORT = "995";
    private static final String USERNAME = "775335103@qq.com";
    private static final String PASSWORD = "WANG2010j523781";
    private static final String FROM = "775335103@qq.com";

    private String[] to;
    private String[] cc;
    private String[] bcc;
    private String subject;
    private String htmlContent;
    private List<String> imagePath;

    public void sendWithImage() throws Exception {
        LOGGER.info(toString());
        Properties props = new Properties();
        props.put("mail.smtp.auth", AUTH ? "true" : "false");
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        SelfAuthenticator authenticator = null;
        if (AUTH) {
            // 如果需要身份认证，则创建一个密码验证器
            authenticator = new SelfAuthenticator(USERNAME, PASSWORD);
        }
        Session session = Session.getDefaultInstance(props, authenticator);

        // 设置标题，收发人
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(FROM));
        if (ArrayUtils.isNotEmpty(to)) {
            message.setRecipients(Message.RecipientType.TO, buildReceiveAddresses(to));
        }
        if (ArrayUtils.isNotEmpty(cc)) {
            message.setRecipients(Message.RecipientType.CC, buildReceiveAddresses(cc));
        }
        if (ArrayUtils.isNotEmpty(bcc)) {
            message.setRecipients(Message.RecipientType.BCC, buildReceiveAddresses(bcc));
        }
        message.setSubject(subject);
        Multipart multipart = new MimeMultipart("related");

        // 设置邮件内容
        StringBuilder sb = new StringBuilder();
        List<String> imageIds = new ArrayList<>();
        for (int i = 0; i < imagePath.size(); i++) {
            sb.append("<img src=\"cid:image").append(i).append("\">");
            imageIds.add("image" + i);
        }
        BodyPart htmlPart = new MimeBodyPart();
        htmlContent = sb.toString() + htmlContent;
        htmlPart.setContent(htmlContent, "text/html;charset=UTF-8");
        multipart.addBodyPart(htmlPart);

        for (int i = 0; i < imagePath.size(); i++) {
            BodyPart imgPart = new MimeBodyPart();
            DataSource fds = new FileDataSource(imagePath.get(i));
            imgPart.setDataHandler(new DataHandler(fds));
            imgPart.setHeader("Content-ID", imageIds.get(i));
            imgPart.setFileName(i + ".png");
            multipart.addBodyPart(imgPart);
        }
        message.setContent(multipart, "text/html;charset=UTF-8");
        Transport.send(message);

        System.out.println(" Sent -| ");
        LOGGER.info("already sent success");
    }

    private static Address[] buildReceiveAddresses(String[] tos) {
        Address[] addresses = new Address[tos.length];
        for (int i = 0; i < tos.length; i++) {
            try {
                addresses[i] = new InternetAddress(tos[i]);
            } catch (AddressException e) {
                e.printStackTrace();
            }
        }
        return addresses;
    }

    public String[] getTo() {
        return to;
    }

    public void setTo(String[] to) {
        this.to = to;
    }

    public String[] getCc() {
        return cc;
    }

    public void setCc(String[] cc) {
        this.cc = cc;
    }

    public String[] getBcc() {
        return bcc;
    }

    public void setBcc(String[] bcc) {
        this.bcc = bcc;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getHtmlContent() {
        return htmlContent;
    }

    public void setHtmlContent(String htmlContent) {
        this.htmlContent = htmlContent;
    }

    public List<String> getImagePath() {
        return imagePath;
    }

    public void setImagePath(List<String> imagePath) {
        this.imagePath = imagePath;
    }

    @Override
    public String toString() {
        return "EmailHelper{" +
                "to=" + Arrays.toString(to) +
                ", cc=" + Arrays.toString(cc) +
                ", bcc=" + Arrays.toString(bcc) +
                ", subject='" + subject + '\'' +
                ", htmlContent='" + htmlContent + '\'' +
                ", imagePath=" + imagePath +
                '}';
    }
}
